package edu.njust.LabSystem.Controller;

import edu.njust.LabSystem.Service.*;
import edu.njust.LabSystem.dto.LaExpDto;
import edu.njust.LabSystem.entity.LabAppointment;
import edu.njust.LabSystem.entity.Seat;
import edu.njust.LabSystem.entity.Student;
import edu.njust.LabSystem.entity.StudentAppointment;
import edu.njust.LabSystem.util.DbUtil;
import edu.njust.LabSystem.util.ResponseUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StuServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    DbUtil dbUtil = new DbUtil();
    LabAppointmentService labAppointmentService = new LabAppointmentService();
    StudentAppointmentService studentAppointmentService = new StudentAppointmentService();
    ExperimentService experimentService = new ExperimentService();
    IStudentService studentService = new IStudentService();
    LabService labService = new LabService();
    SeatService seatService = new SeatService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");

        if ("list".equals(action)) {
            this.appList(request, response);
        } else if ("save".equals(action)) {
            try {
                this.appSave(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("del".equals(action)) {
            this.delete(request, response);
        }
    }


    protected void appList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String uid = request.getSession().getAttribute("uid").toString();
        Student stu = studentService.getStudentById(uid);

        try {

            List<LaExpDto> las = labAppointmentService.getLabApps();

            //获取已选课程的列表 lls已选 las未选
            List<LaExpDto> lls = new ArrayList<>();
            List<LaExpDto> lws = new ArrayList<>();
            List<LaExpDto> lys = new ArrayList<>();

            for (LaExpDto la : las) {

                //判断是否本班级,不是直接跳过
                if (!(stu.getClassid().equals(la.getClassid()))) {
                    continue;
                } else {
                    if (!la.getType()) {
                        lys.add(la); //实验课程
                    } else {
                        StudentAppointment sa = studentAppointmentService.getByStudentandExperiment(uid, la.getExperiment());
                        if (sa != null) {
                            lls.add(la); //已选
                            la.setSeat(sa.getSeat());
                        } else {
                            lws.add(la);  //未选
                        }
                    }
                }
            }
            //坐次
            String labid;
            List<Seat> seats;
            if(lws.size()>0) {
                labid = lws.get(0).getLab();
                seats = seatService.getSeatsById(labid);
            }else if(lws.size()>0){
                labid = lls.get(0).getLab();
                seats = seatService.getSeatsById(labid);
            }else{
                labid = las.get(0).getLab();
                seats=seatService.getSeatsById(labid);
            }
            request.setAttribute("las", las);
            request.setAttribute("lls", lls);
            request.setAttribute("lws", lws);
            request.setAttribute("seats", seats);
            request.setAttribute("mainpage", "public/deault.jsp");
            request.getRequestDispatcher("stuhome.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void appSave(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String eid = request.getParameter("eid");
        String uid = request.getParameter("uid");
        String lid = "000"+request.getParameter("lid");
        String sid = request.getParameter("sid");
//        String appoint_date = request.getParameter("appoint_date");
        String appoint_time = request.getParameter("appoint_time");

        LabAppointment lap = labAppointmentService.getLabAppointmentByExperiment(uid);

        StudentAppointment sa = new StudentAppointment(lid, sid, eid, lap.getAppoint_date(), Integer.parseInt(appoint_time), uid);

        try {
            //增加预约
            studentAppointmentService.insertStudentAppointment(sa);
            //更新座次
            seatService.updateSeat(sid,"1");

            JSONObject result = new JSONObject();
            result.put("success", true);
            ResponseUtil.write(result, response);

//            request.getRequestDispatcher("/app?action=list").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) {

        String uid = request.getParameter("uid");
        String eid = request.getParameter("eid");
        StudentAppointment del = new StudentAppointment();
        del.setStudent(uid);
        del.setExperiment(eid);
        JSONObject result = new JSONObject();

        //获取座次
        StudentAppointment sae = studentAppointmentService.getByStudentandExperiment(uid, eid);

        try {
            Integer r = studentAppointmentService.deleteStudentAppointment(del);
            //删除占座信息
            seatService.updateSeat(sae.getSeat(),"0");

            if (r > 0) {
                result.put("success", true);
                result.put("delNums", r);
            } else {
                result.put("errorMsg", "删除失败");
            }
            ResponseUtil.write(result, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}
